<template>
    <div class="login_container">
        <el-form class="login_form" :model="loginFrom" :rules="rules" ref="loginFromRef">
            <h1>{{ title }}</h1>
            <el-form-item prop="username">
                <el-input :prefix-icon="User" v-model="loginFrom.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input :prefix-icon="Lock" type="password" v-model="loginFrom.password" show-password></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :loading="loading" @click="handleLogin">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts" name="Login">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue';
import { userLogin } from '@/api/management/user'
import { ElMessage } from 'element-plus';
import type { FormRules, FormInstance } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/user';
import type { UserLoginRequest } from '@/api/management/user/types';
import CryptoJS from 'crypto-js';

const title = import.meta.env.VITE_APP_TITLE

const loading = ref(false)
const loginFromRef = ref<FormInstance>()
const loginFrom = reactive<UserLoginRequest>({ username: '', password: '' })

// 自定义用户名验证方法
const validateUsername = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else {
        const pattern = /^[a-zA-Z0-9]{5,}$/
        if (!pattern.test(value)) {
            callback(new Error('用户名必须由数字和字母组成且长度大于5'))
        }
        callback()
    }
}

// 自定义密码验证方法
const validatePassword = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        const pattern = /^[a-zA-Z0-9]{6,}$/
        if (!pattern.test(value)) {
            callback(new Error('密码必须由数字和字母组成且长度大于6'))
        }
        callback()
    }
}

const rules = reactive<FormRules<UserLoginRequest>>({
    username: [{ validator: validateUsername, trigger: 'blur' }],
    password: [{ validator: validatePassword, trigger: 'blur' }],
})

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const handleLogin = async () => {
    await loginFromRef.value?.validate()
    try {
        loading.value = true
        const { password, ...rest } = loginFrom
        const data = await userLogin({ password: CryptoJS.SHA256(password).toString(), ...rest })
        if (data.code === 200) {
            const token = data.data.tokenValue
            userStore.setUserToken(token)
            const redirect: any = route.query.redirect
            router.push(redirect || '/')
        } else {
            ElMessage.error(`${data.message}`)
        }
        loading.value = false
    } catch (error) {
        loading.value = false
    }
}
</script>

<style scoped lang="scss">
.login_container {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;

    .login_form {
        width: 30%;
        min-width: 400px;
        padding: 40px;
        border-radius: 10px;

        h1 {
            font-size: 40px;
            margin-bottom: 20px;
            text-align: center;
        }

        .el-button {
            width: 100%;
            height: 50px;
        }

        .el-input {
            height: 50px;
        }
    }
}
</style>